package com.llg.service;

import com.llg.model.FormulaVO;
import com.llg.model.code.CommonCode;
import com.llg.model.response.DataResult;
import com.llg.model.response.PageResult;
import com.llg.model.response.ResponseResult;
import com.llg.pojo.FormulaPO;
import com.llg.repository.FormulaPORepository;
import com.llg.util.ConvertUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class FormulaService {

    private final FormulaPORepository formulaPoRepository;

    @Autowired
    public FormulaService(FormulaPORepository formulaPoRepository) {
        this.formulaPoRepository = formulaPoRepository;
    }

    public PageResult<FormulaVO> findAll() {
        List<FormulaPO> all = formulaPoRepository.findAll();
        List<FormulaVO> collect = ConvertUtils.povoListConvert(all, FormulaVO.class);
        return new PageResult<>(CommonCode.SUCCESS, collect.size(), 1, collect);
    }


    public PageResult<FormulaVO> findList(Integer currentPage, Integer pageSize, FormulaVO formulaVo) {
        return null;
    }

    public DataResult<FormulaVO> findById(Integer id) {
        FormulaPO formulaPo = formulaPoRepository.findById(id).orElse(null);
        FormulaVO formulaVo = ConvertUtils.povoConvert(formulaPo, FormulaVO.class);
        return new DataResult<>(CommonCode.SUCCESS,formulaVo );
    }

    public DataResult<FormulaVO> add(FormulaVO formulaVo) {
        FormulaPO formulaPo = ConvertUtils.povoConvert(formulaVo, FormulaPO.class);
        FormulaPO save = formulaPoRepository.save(formulaPo);
        formulaVo.setId(save.getId());
        return new DataResult<>(CommonCode.SUCCESS, formulaVo);
    }

    public ResponseResult delete(Integer id) {
        formulaPoRepository.deleteById(id);
        return new ResponseResult(CommonCode.SUCCESS);
    }

    public ResponseResult update(FormulaVO formulaVo) {
        Optional<FormulaPO> optional = formulaPoRepository.findById(formulaVo.getId());
        if (optional.isPresent()){
            FormulaPO formulaPo = ConvertUtils.povoConvert(formulaVo, FormulaPO.class);
            formulaPoRepository.save(formulaPo);
            return new ResponseResult(CommonCode.SUCCESS);
        }
        return new ResponseResult(CommonCode.NO_EXIST_ID);
    }
}
